package com.code.zjm.helper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.code.zjm.entity.User;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by ZJM on 2017/4/27.
 * 数据库管理类
 */

public class DBHelper {
    //数据库名称
    public static final String DB_NAME = "contact";
    //表名
    public static final String TABLE_NAME = "user";
    //版本
    public static final int VERSION = 4;
    //SQLite 对象
    public static SQLiteDatabase dbInstance;
    //MyHelper 对象
    private MyDBHelper myDBHelper;
    //上下文对象
    private Context context;

    /**
     * 初始化数据构造器
     *
     * @param context context
     */
    public DBHelper(Context context) {
        this.context = context;
    }

    /**
     * 打开数据库，进行数据库写入操作
     */
    public void openDatabase() {
        //数据库不存在时创建
        if (dbInstance == null) {
            myDBHelper = new MyDBHelper(context, DB_NAME, VERSION);
            dbInstance = myDBHelper.getWritableDatabase();
        }
    }

    /**
     * 获得数据库中所有的用户，将每一个用户放到一个 map 中去，然后再将 map 放到 list 里面去返回
     *
     * @param privacy 隐私联系人
     * @return list
     */

    public ArrayList<HashMap<String, Object>> getAllUser(boolean privacy) {
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        Cursor cursor;
        if (privacy) {
            cursor = dbInstance.query(TABLE_NAME,
                    new String[]{"_id", "name", "mobile_phone", "office_phone", "family_phone", "address", "other_contact", "email", "position", "company", "zip_code", "remark", "image_id"},
                    "privacy=1",
                    null,
                    null,
                    null,
                    null);
        } else {
            cursor = dbInstance.query(TABLE_NAME,
                    new String[]{"_id", "name", "mobile_phone", "office_phone", "family_phone", "address", "other_contact", "email", "position", "company", "zip_code", "remark", "image_id"},
                    "privacy=0",
                    null,
                    null,
                    null,
                    null);
        }

        //将结果集放入 List 中
        while (cursor.moveToNext()) {
            HashMap<String, Object> item = new HashMap<>();
            item.put("_id", cursor.getInt(cursor.getColumnIndex("_id")));
            item.put("name", cursor.getString(cursor.getColumnIndex("name")));
            item.put("mobile_phone", cursor.getString(cursor.getColumnIndex("mobile_phone")));
            item.put("office_phone", cursor.getString(cursor.getColumnIndex("office_phone")));
            item.put("family_phone", cursor.getString(cursor.getColumnIndex("family_phone")));
            item.put("address", cursor.getString(cursor.getColumnIndex("address")));
            item.put("other_contact", cursor.getString(cursor.getColumnIndex("other_contact")));
            item.put("email", cursor.getString(cursor.getColumnIndex("email")));
            item.put("position", cursor.getString(cursor.getColumnIndex("position")));
            item.put("company", cursor.getString(cursor.getColumnIndex("company")));
            item.put("zip_code", cursor.getString(cursor.getColumnIndex("zip_code")));
            item.put("remark", cursor.getString(cursor.getColumnIndex("remark")));
            item.put("image_id", cursor.getInt(cursor.getColumnIndex("image_id")));
            list.add(item);
        }

        return list;
    }

    /**
     * 往数据库里面的user表插入一条数据，若失败返回-1
     *
     * @param user 联系人
     * @return 失败返回-1
     */
    public long insert(User user) {
        ContentValues values = new ContentValues();
        values.put("name", user.getUsername());
        values.put("mobile_phone", user.getMobilePhone());
        values.put("office_phone", user.getOfficePhone());
        values.put("family_phone", user.getFamilyPhone());
        values.put("address", user.getAddress());
        values.put("other_contact", user.getOtherContact());
        values.put("email", user.getEmail());
        values.put("position", user.getPosition());
        values.put("company", user.getCompany());
        values.put("zip_code", user.getZipCode());
        values.put("remark", user.getRemark());
        values.put("image_id", user.getImageId());
        values.put("privacy", user.getPrivacy());
        return dbInstance.insert(TABLE_NAME, null, values);
    }


    /**
     * 修改 联系人 信息
     *
     * @param user user
     */
    public boolean modify(User user) {
        ContentValues values = new ContentValues();
        values.put("name", user.getUsername());
        values.put("mobile_phone", user.getMobilePhone());
        values.put("office_phone", user.getOfficePhone());
        values.put("family_phone", user.getFamilyPhone());
        values.put("address", user.getAddress());
        values.put("other_contact", user.getOtherContact());
        values.put("email", user.getEmail());
        values.put("position", user.getPosition());
        values.put("company", user.getCompany());
        values.put("zip_code", user.getZipCode());
        values.put("remark", user.getRemark());
        values.put("image_id", user.getImageId());

        System.out.println(">>>>>>_id: " + user.get_id() + " <<<<<<<< OK");

        int row = dbInstance.update(TABLE_NAME, values, "_id=?", new String[]{String.valueOf(user.get_id())});
        System.out.println(">>>>>> row: " + row);
        return row > 0;
    }

    public void delete(int _id) {
        dbInstance.delete(TABLE_NAME, "_id=?", new String[]{String.valueOf(_id)});
    }

    public void deleteAll(int privacy) {
        dbInstance.delete(TABLE_NAME, "privacy=?", new String[]{String.valueOf(privacy)});
    }

    public int getTotalCount() {
        Cursor cursor = dbInstance.query(TABLE_NAME, new String[]{"count(*)"}, null, null, null, null, null);
        cursor.moveToNext();
        return cursor.getInt(0);
    }


    public ArrayList<HashMap<String, Object>> getUsers(String condition, boolean privacy) {
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        String strSelection = "";
        if (privacy) {
            strSelection = "and privacy = 1";
        } else {
            strSelection = "and privacy = 0";
        }
        String sql = "select * from " + TABLE_NAME + " where 1=1 and (name like '%" + condition + "%' " +
                "or mobile_phone like '%" + condition + "%' or family_phone like '%" + condition + "%' " +
                "or office_phone like '%" + condition + "%')" + strSelection;
        Cursor cursor = dbInstance.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            HashMap<String, Object> item = new HashMap<>();
            item.put("_id", cursor.getInt(cursor.getColumnIndex("_id")));
            item.put("name", cursor.getString(cursor.getColumnIndex("name")));
            item.put("mobile_phone", cursor.getString(cursor.getColumnIndex("mobile_phone")));
            item.put("office_phone", cursor.getString(cursor.getColumnIndex("office_phone")));
            item.put("family_phone", cursor.getString(cursor.getColumnIndex("family_phone")));
            item.put("address", cursor.getString(cursor.getColumnIndex("address")));
            item.put("other_contact", cursor.getString(cursor.getColumnIndex("other_contact")));
            item.put("email", cursor.getString(cursor.getColumnIndex("email")));
            item.put("position", cursor.getString(cursor.getColumnIndex("position")));
            item.put("company", cursor.getString(cursor.getColumnIndex("company")));
            item.put("zip_code", cursor.getString(cursor.getColumnIndex("zip_code")));
            item.put("remark", cursor.getString(cursor.getColumnIndex("remark")));
            item.put("image_id", cursor.getInt(cursor.getColumnIndex("image_id")));
            list.add(item);
        }
        return list;
    }

    public void deleteMarked(ArrayList<Integer> deleteId) {
        StringBuffer strDeleteId = new StringBuffer();
        strDeleteId.append("_id=");
        for (int i = 0; i < deleteId.size(); i++) {
            if (i != deleteId.size() - 1) {
                strDeleteId.append(deleteId.get(i) + " or _id=");
            } else {
                strDeleteId.append(deleteId.get(i));
            }


        }
        dbInstance.delete(TABLE_NAME, strDeleteId.toString(), null);
        System.out.println(strDeleteId.toString());

    }

    public void backupData(boolean privacy) {
        StringBuffer sqlBackup = new StringBuffer();
        Cursor cursor = null;
        if (privacy) {
            cursor = dbInstance.query(TABLE_NAME,
                    new String[]{"_id", "name", "mobile_phone", "office_phone", "family_phone", "address", "other_contact", "email", "position", "company", "zip_code", "remark", "image_id,privacy"},
                    "privacy=1",
                    null,
                    null,
                    null,
                    null);
        } else {
            cursor = dbInstance.query(TABLE_NAME,
                    new String[]{"_id", "name", "mobile_phone", "office_phone", "family_phone", "address", "other_contact", "email", "position", "company", "zip_code", "remark", "image_id,privacy"},
                    "privacy=0",
                    null,
                    null,
                    null,
                    null);
        }


        while (cursor.moveToNext()) {
            sqlBackup.append("insert into " + TABLE_NAME + "(name,mobile_phone,office_phone,family_phone,address,other_contact,email,position,company,zip_code,remark,image_id,privacy)")
                    .append(" values ('")
                    .append(cursor.getString(cursor.getColumnIndex("name"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("mobile_phone"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("office_phone"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("family_phone"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("address"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("other_contact"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("email"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("position"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("company"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("zip_code"))).append("','")
                    .append(cursor.getString(cursor.getColumnIndex("remark"))).append("',")
                    .append(cursor.getInt(cursor.getColumnIndex("image_id"))).append(",")
                    .append(cursor.getInt(cursor.getColumnIndex("privacy")))
                    .append(");").append("\n");
        }
        saveDataToFile(sqlBackup.toString(), privacy);

    }

    /**
     * 保存数据
     *
     * @param strData
     * @param privacy
     */
    private void saveDataToFile(String strData, boolean privacy) {
        String fileName = "";
        if (privacy) {
            fileName = "priv_data.bk";
        } else {
            fileName = "comm_data.bk";
        }
        try {
            String SDPATH = Environment.getExternalStorageDirectory() + "/";
            File fileParentPath = new File(SDPATH + "zpContactData/");
            fileParentPath.mkdirs();
            File file = new File(SDPATH + "zpContactData/" + fileName);
            System.out.println("the file previous path = " + file.getAbsolutePath());

            file.createNewFile();
            System.out.println("the file next path = " + file.getAbsolutePath());
            FileOutputStream fos = new FileOutputStream(file);

            fos.write(strData.getBytes());
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 恢复数据
     *
     * @param fileName
     */
    public void restoreData(String fileName) {
        try {
            String SDPATH = Environment.getExternalStorageDirectory() + "/";
            File file = null;
            if (fileName.endsWith(".bk")) {
                file = new File(SDPATH + "zpContactData/" + fileName);
            } else {
                file = new File(SDPATH + "zpContactData/" + fileName + ".bk");
            }
            BufferedReader br = new BufferedReader(new FileReader(file));
            String str = "";
            while ((str = br.readLine()) != null) {
                System.out.println(str);
                dbInstance.execSQL(str);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean findFile(String fileName) {
        String SDPATH = Environment.getExternalStorageDirectory() + "/";
        File file = null;
        if (fileName.endsWith(".bk")) {
            file = new File(SDPATH + "zpContact/" + fileName);
        } else {
            file = new File(SDPATH + "zpContact/" + fileName + ".bk");
        }

        if (file.exists()) {
            return true;
        } else {
            return false;
        }


    }

}

